package web.pre;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jdt.internal.compiler.codegen.BranchLabel;

import com.alibaba.fastjson.JSON;

import entity.User;
import service.EasyBuyService;
import utils.ReturnResult;

public class userAddServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
        //一个Servlet可以处理多个机试
		String action = request.getParameter("action");
		if(action!=null){
			switch (action) {
			case "doRegister":
				//进行注册操作
				doRegister(request,response);
				break;
			case "toRegister":
				//跳转到注册页面
				request.getRequestDispatcher("Regist.jsp").forward(request, response);
				break;

			default:
				
				break;
			}
		}else {
			response.sendRedirect("Regist.jsp");
		}



	}
	private void doRegister(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
		// TODO Auto-generated method stub
		User user =new User();
		user.setLoginName(request.getParameter("loginName"));
		user.setUserName(request.getParameter("userName"));
		user.setPassword(request.getParameter("password"));
		user.setSex(Integer.parseInt(request.getParameter("sex")));
		user.setIdentityCode(request.getParameter("identityCode"));
		user.setEmail(request.getParameter("email"));
		user.setMobile(request.getParameter("mobile"));
		user.setType(Integer.parseInt(request.getParameter("type")));

		EasyBuyService sec=new EasyBuyService();
		boolean count= sec.userAdd(user);
		PrintWriter out =response.getWriter();
		ReturnResult result=new ReturnResult();
		if(count){
			result.setStatus(1);
			result.setMessage("注册成功");
		}else{
			result.setStatus(0);
			result.setMessage("注册失败");
		}
		String str=JSON.toJSONString(result);
		out.print(str);
		out.flush();
		out.close();
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

}
